﻿// <copyright file="HandleFormListBox.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-01-29</date>
// <summary>HandleFormListBox class definition</summary>

namespace Microsoft.WebAnalytics.Behaviors.FormTrackers
{
    using System;
    using System.Windows.Controls;
    using Microsoft.WebAnalytics.Contracts;

    /// <summary>
    /// Handle the Form events for ListBox.SelectionChanged
    /// </summary>
    [FormTracker(typeof(ListBox))]
    public class HandleFormListBox : ITrackFormControl
    {
        #region Fields
        /// <summary>
        /// The event handler
        /// </summary>
        private EventHandler<FormEventArgs> handler;
        #endregion

        #region ITrackFormControl Members

        /// <summary>
        /// Attach to the ListBox selection changed events
        /// </summary>
        /// <param name="control">the ListBox control</param>
        /// <param name="eventHandler">the event handler to route events to</param>
        public void AttachEvents(Control control, EventHandler<FormEventArgs> eventHandler)
        {
            System.Diagnostics.Debug.Assert(control != null, "control must not be null.");

            System.Diagnostics.Debug.Assert(eventHandler != null, "handler must not be null.");

            this.handler = eventHandler;

            var listBox = control as ListBox;

            listBox.SelectionChanged += new SelectionChangedEventHandler(this.SelectionChanged);
        }

        /// <summary>
        /// Route the selection changed event
        /// </summary>
        /// <param name="sender">the ListBox</param>
        /// <param name="e">the selection changed event arguments</param>
        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var formEvent = new FormEventArgs
            {
                Control = sender as Control,
                EventName = "SelectionChanged",
                InnerEvent = e
            };

            this.handler(this, formEvent);
        }

        #endregion
    }
}
